<!--
  * 文件上传
  * 
  *
-->
<template>
  <div class="clearfix">
    <a-upload
      accept=".png,.jpg,.jpeg,.bmp"
      list-type="picture-card"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      :customRequest="customRequest"
      :headers="{ 'x-access-token': useUserStore().getToken }"
      @change="handleChange"
    >
      <img style="width: 100%; height: 100%" v-if="imageUrl" :src="imageUrl" alt="avatar" />
    </a-upload>
  </div>
</template>
<script setup>
  import { computed, ref, watch } from 'vue';
  import { Modal, message } from 'ant-design-vue';
  import { fileApi } from '/src/api/support/file-api';
  import { useUserStore } from '/@/store/modules/system/user';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { FILE_FOLDER_TYPE_ENUM } from '/@/constants/support/file-const';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { rzApplyApi } from '/@/api/system/rzApply';

  const props = defineProps({
    value: String,
    buttonText: {
      type: String,
      default: '点击上传附件',
    },
    showUploadBtn: {
      type: Boolean,
      default: true,
    },
    defaultFileList: {
      type: Array,
      default: () => [],
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    // 最多上传文件数量
    maxUploadSize: {
      type: Number,
      default: 1,
    },
    maxSize: {
      type: Number,
      default: 1,
    },
    // 上传的文件类型
    accept: {
      type: String,
      default: '',
    },
    // 文件上传类型
    folder: {
      type: Number,
      default: FILE_FOLDER_TYPE_ENUM.COMMON.value,
    },
    // 上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card
    listType: {
      type: String,
      default: 'picture-card',
    },
    mode: 'front',
  });
  const imageUrl = ref('');
  // 图片类型的后缀名
  const imgFileType = ['jpg', 'jpeg', 'png', 'gif'];

  // 重新修改图片展示字段
  const files = computed(() => {
    let res = [];
    if (props.defaultFileList && props.defaultFileList.length > 0) {
      props.defaultFileList.forEach((element) => {
        element.url = element.fileUrl;
        element.name = element.fileName;
        res.push(element);
      });
      return res;
    }
    return res;
  });
  // -------------------- 逻辑 --------------------

  const fileList = ref([]);

  watch(
    files,
    (value) => {
      fileList.value = value;
    },
    {
      immediate: true,
    }
  );

  const emit = defineEmits(['update:value', 'change']);
  function beforeUpload(file, files) {
    console.log(file.raw);
    const promise = new Promise((resolve, reject) => {
      const isLt4M = file.size / 1024 / 1024 < 4;
      if (!isLt4M) {
        message.error('上传图片大小不能超过 4MB!');
        reject();
      }
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function () {
        //让页面中的img标签的src指向读取的路径
        const img = new Image();
        img.src = reader.result;
        if (img.complete) {
          //如果存在浏览器缓存中
          if (img.width > 4096 || img.height > 4096) {
            message.error('上传图片最长边不大于 4096!');
            reject();
          } else {
            URL.createObjectURL(file);
            // 解析成Base64
            imageUrl.value = reader.result;
            resolve(file);
          }
        } else {
          img.onload = function () {
            console.log(img.width);
            if (img.width > 4096 || img.height > 4096) {
              message.error('上传图片最长边不大于 4096!');
              reject();
            } else {
              URL.createObjectURL(file);
              // 解析成Base64
              imageUrl.value = reader.result;
              resolve(file);
            }
          };
        }
      };
    });
    console.log(promise);
    return promise;
  }
  // 二进制格式
  function dataURItoBlob(dataURI) {
    // base64 解码
    let byteString = window.atob(dataURI.split(',')[1]);
    let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    let ab = new ArrayBuffer(byteString.length);
    let ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ab], {
      type: mimeString,
    });
  }
  const customRequest = async (options) => {
    SmartLoading.show();
    try {
      const file = options.file;
      const url = dataURItoBlob(imageUrl.value);
      if (props.mode == 'front') {
        const formData1 = new FormData();
        formData1.append('file', url);
        formData1.append('bussNo', 'rzApplyStore.getBussNo');
        formData1.append('idCardType', 'Z');
        const res = await rzApplyApi.ocrUpload(formData1);
        if (res.code == 0) {
        }
      } else {
        const formData1 = new FormData();
        formData1.append('file', url);
        formData1.append('bussNo', 'rzApplyStore.getBussNo');
        formData1.append('idCardType', 'F');
        const res = await rzApplyApi.ocrUpload(formData1);
        if (res.code == 0) {
        }
      }
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  };

  function handleChange(info) {
    let fileStatus = info.file.status;
    let file = info.file;
  }

  const showErrorModalFlag = ref(true);
  const showErrorMsgOnce = (content) => {
    if (showErrorModalFlag.value) {
      Modal.error({
        title: '提示',
        content: content,
        okType: 'danger',
        centered: true,
        onOk() {
          showErrorModalFlag.value = true;
        },
      });
      showErrorModalFlag.value = false;
    }
  };

  // ------------------------ 清空 上传 ------------------------
  function clear() {
    imageUrl.value = '';
  }

  defineExpose({
    clear,
  });
</script>
<style lang="less" scoped>
  :deep(.ant-upload-picture-card-wrapper) {
    display: flex;
    width: 100%;
    height: 100%;
  }
  /deep/ .ant-upload-wrapper,
  /deep/.ant-upload-list,
  /deep/.ant-upload {
    width: 100% !important;
    height: 100% !important;
  }
</style>
